package com.genius.dingding.util;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiCallBackGetCallBackRequest;
import com.dingtalk.api.request.OapiCallBackRegisterCallBackRequest;
import com.dingtalk.api.request.OapiCallBackUpdateCallBackRequest;
import com.dingtalk.api.response.OapiCallBackGetCallBackResponse;
import com.dingtalk.api.response.OapiCallBackRegisterCallBackResponse;
import com.dingtalk.api.response.OapiCallBackUpdateCallBackResponse;
import com.taobao.api.ApiException;

public class CallBackHelper {
	
	public String callBack(String token,String aesKey,String reciveUrl){
		
	
		String accessToken = GetDingDing.getInstance().getToken();
//		System.out.println("callBakUrl---------"+callBakUrl);
		DingTalkClient  client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/call_back/get_call_back");
		OapiCallBackGetCallBackRequest req = new OapiCallBackGetCallBackRequest();
		req.setTopHttpMethod("GET");
		OapiCallBackGetCallBackResponse rsp;
		String result = "";
		try {
			rsp = client.execute(req,accessToken);
			JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
			if("0".equals(jsonObject.getString("errcode"))){
				result = updateCorpCallBack(token, aesKey, reciveUrl);
				System.out.println(result);
			}else{
				result = registerCorpCallBack(token, aesKey, reciveUrl);
				System.out.println(result);
			}
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public String registerCorpCallBack(String token,String aesKey,String callBakUrl) throws ApiException {
			
		DingTalkClient client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/call_back/register_call_back");
		OapiCallBackRegisterCallBackRequest request = new OapiCallBackRegisterCallBackRequest();
		request.setUrl(callBakUrl);
		request.setAesKey(aesKey);
		request.setToken(token);
		request.setCallBackTag(CorpCallBackTypeEnum.getAllTag());
		OapiCallBackRegisterCallBackResponse response = client.execute(request,GetDingDing.getInstance().getToken());
		return response.getBody();
    }
	public String updateCorpCallBack(String token,String aesKey,String callBakUrl) throws ApiException {
		DingTalkClient  client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/call_back/update_call_back");
		OapiCallBackUpdateCallBackRequest request = new OapiCallBackUpdateCallBackRequest();request.setUrl(callBakUrl);
		request.setAesKey(aesKey);
		request.setToken(token);
		request.setCallBackTag(CorpCallBackTypeEnum.getAllTag());
		OapiCallBackUpdateCallBackResponse response = client.execute(request,GetDingDing.getInstance().getToken());
		return response.getBody();
    }
}
